package leetcode;

import java.util.*;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-03-14 17:25
 **/
public class LeetCode599 {

    public String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < list1.length; i++) {
            map.put(list1[i], i);
        }
        List<String> ans = new ArrayList<>();
        int sum = Integer.MAX_VALUE;
        for (int i = 0; i < list2.length; i++) {
            if (map.containsKey(list2[i])) {
                int indexSum = i + map.get(list2[i]);
                if (indexSum < sum) {
                    ans.clear();
                    ans.add(list2[i]);
                    sum = indexSum;
                } else if (indexSum == sum) {
                    ans.add(list2[i]);
                }
            }
        }
        return ans.toArray(new String[0]);
    }

}
